#import "MO2XMLManagedObjectExporter.h"


@implementation MO2XMLManagedObjectExporter

- (id)init {
	self = [super init];
	if(self) {
		[self setManagedObject:nil];
		[self setProperties:nil];
	}
	return self;
}

- (id)initWithManagedObject:(NSManagedObject *)mo {
	self = [super init];
	if(self) {
		[self setProperties:nil];
		[self setManagedObject:mo];
	}
	return self;
}

+ (id)managedObjectExporterWithManagedObject:(NSManagedObject *)mo {
	return [[[MO2XMLManagedObjectExporter alloc] initWithManagedObject:mo] autorelease];
}

- (void)dealloc {
	[managedObject release];
	[properties release];
	
	[super dealloc];
}

- (NSManagedObject *)managedObject {
    return managedObject;
}

- (void)setManagedObject:(NSManagedObject *)value {
	[value retain];
	[managedObject release];
	managedObject = value;
}

- (NSDictionary *)managedObjectAsDictionary {
	NSManagedObject *object = [self managedObject];
	if(object != nil) {
		NSEntityDescription *entityDescription = [object entity];
		NSDictionary *attributes = [entityDescription attributesByName];
		NSArray *attributesKeys = [attributes allKeys];
		
		NSMutableDictionary *dict = [[[NSMutableDictionary alloc] init] autorelease];
		
		NSEnumerator *dictEnumerator = [attributesKeys objectEnumerator];
		id attribute;
		while(attribute = [dictEnumerator nextObject]) {
			id value = [object valueForKey:attribute];
		
			if (value != nil) {
				[dict setObject:value forKey:attribute];
			} 			
		}
		
		// Set the properties
		NSArray *propertiesKeys = [[self properties] allKeys];
		NSEnumerator *propertiesKeysEnumerator = [propertiesKeys objectEnumerator];
		id propertyKey;
		while(propertyKey = [propertiesKeysEnumerator nextObject]) {
			[dict setValue:[[self properties] valueForKey:propertyKey] forKey:propertyKey];
		}
		
		return dict;
	}
	
	return nil;
}

- (NSDictionary *)properties {
	return properties;
}

- (void)setProperties:(NSDictionary *)value {
	[value retain];
	[properties release];
	properties = value;
}

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag {
	NSDictionary *managedObjectAsDict = [self managedObjectAsDictionary];
	if(managedObjectAsDict != nil) {
		return [[self  managedObjectAsDictionary] writeToFile:path atomically:flag];
	}
	
	return NO;	
}

@end
